package com.quectel.util.common;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.quectel.util.ex.common.ImageGenException;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * 二维码帮助类
 */
public class QRCodeUtils {
    /**
     * 生成二维码
     *
     * @param content 内容
     * @param width   大小
     * @param height  高度
     * @param format  png jpg
     * @param out     输出目的地
     */
    public static void create(String content, int width, int height, String format, OutputStream out) {
        //定义二维码的参数
        Map<EncodeHintType, Object> hints = new HashMap();
        //设置编码
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        //设置纠错等级
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        hints.put(EncodeHintType.MARGIN, 0);
        //生成二维码
        try {
            BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
            MatrixToImageWriter.writeToStream(bitMatrix, format, out);
        } catch (Exception e) {
            throw new ImageGenException("QR generate error");
        }
    }

    public static String read(InputStream in) {
        try {
            MultiFormatReader multiFormatReader = new MultiFormatReader();
            BufferedImage image = ImageIO.read(in);
            //定义二维码参数
            Map<DecodeHintType, Object> hints = new HashMap();
            hints.put(DecodeHintType.CHARACTER_SET, "utf-8");

            //获取读取二维码结果
            BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));
            Result result = multiFormatReader.decode(binaryBitmap, hints);
            return result.getText();
        } catch (Exception e) {
            throw new ImageGenException("Read QR content error");
        }
    }

    public static void main(String[] args) throws FileNotFoundException {
        create("http://www.baidu.com", 500, 500, "png",
                new FileOutputStream("/Users/cl/Desktop/1.png"));
    }
}
